package cn.kawa.service.impl;

import cn.kawa.domain.MovieTicket;
import cn.kawa.domain.User;
import cn.kawa.feign.MovieFeignClient;
import cn.kawa.mapper.UserMapper;
import cn.kawa.result.JsonResult;
import cn.kawa.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author director
 * @since 2022-09-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private MovieFeignClient movieFeignClient;

    /**
     * 需求2：传入要购买的电影票Id，调用电影服务进行购买，购买成功扣减用户余额
     */
    @Override
    public JsonResult buy(Long userId, Long movieId) {
        JsonResult buy = movieFeignClient.buy(userId, movieId);
        ObjectMapper objectMapper = new ObjectMapper();
        MovieTicket movieTicket = objectMapper.convertValue(buy.getData(), MovieTicket.class);
        User user = selectById(userId);
        user.setBalance(user.getBalance()-movieTicket.getPrice());
        updateById(user);
        return JsonResult.success("购买成功");
    }
    /**
     * 需求3：新增用户时，保存用户信息，并调用电影服务，随机送一张电影票
     */
    @Override
    public JsonResult give(User user) {
        insert(user);
        return movieFeignClient.give(user.getId());
    }


}
